package wyu.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dto.Result;
import com.entity.Category;
import com.entity.PostBar;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import wyu.mapper.PostBarMapper;
import wyu.service.feign.CategoryBarService;
import wyu.service.feign.CategoryFeign;
import wyu.service.feign.UserBarService;
import wyu.service.feign.PostFeign;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fengyukang 2022.10.26
 */
@Service
public class PostBarServiceImpl extends ServiceImpl<PostBarMapper, PostBar> implements PostBarService {
    @Resource
    UserBarService userBarService;
    @Resource
    CategoryBarService categoryBarService;
    @Resource
    CategoryFeign categoryFeign;
    @Resource
    PostFeign postFeign;
    /**
     * 查询所有贴吧详细信息列表
     * @return {@link Result} 其中data为贴吧对象{@link PostBar}
     */
    @Override
    public Result getlist() {
        List<PostBar> postBars = list();
        for (PostBar postBar : postBars) {
            int barId = postBar.getId();//获取每个贴吧的id
            postBar.setPeopleNum(userBarService.getCount(barId));//调用user_bar-service微服务获取贴吧关注人数
            int id = categoryBarService.getCategory(barId);//调用category_bar-provider获取对应类别id
            if (id==0){
                postBar.setCategory("未分类~");
                continue;
            }
            //根据类别id获取类别名称
            Category category = categoryFeign.getById(id);
            System.out.println(category);
            String name = category.getName();
            //封装
            postBar.setCategory(name);//设置类别名称
            postBar.setPostNum(postFeign.getPostNumByBarId(barId));//设置贴子数
        }
        System.out.println(postBars);
        return Result.ok(postBars);
    }

    @Override
    @Transactional
    public Result add(String name, String categoryId, String describe, MultipartFile image) {
        PostBar postBar = new PostBar();
        postBar.setName(name);
        postBar.setDescribe(describe);
        boolean save = save(postBar);
        PostBar bar = query().eq("NAME", name).one();
        int barId = bar.getId();
        //todo 有bug，相同名称的贴吧会导致。
        boolean isOk = categoryBarService.addRelevancy(barId, Integer.parseInt(categoryId));
        if (!save || !isOk){
            return Result.fail(900,"添加失败");
        }
        return Result.ok();
    }

    @Override
    public Result setRecommendBars(List<Integer> barIds) {
        List<PostBar> postBarList = new ArrayList<>();
        for (Integer barId : barIds) {
            PostBar postBar = getById(barId);
            postBar.setSetRecommend((byte) 1);
            postBarList.add(postBar);
        }
        boolean isUpdate = updateBatchById(postBarList);
        if (!isUpdate){
            return Result.fail(900,"设置失败");
        }
        //todo 将所有贴吧推荐设为0

        return Result.ok();
    }
    /**
     * 根据条件（参数可以选择性发送）获取贴吧列表
     * 获取 贴吧列表信息的同时 获取当前登录用户（session中的user）和各贴吧的加入关系
     * @param
     * @param getRecommendBars 获取推荐贴吧 1获取推荐  0正常获取所有贴吧（默认）
     * @param unameIndex 查询某用户加入的贴吧
     * @param searchWd 搜索贴吧（按名称或 贴吧id 搜索）
     * @param searchType 0贴吧名称（默认）  1贴吧编号
     * @param sortType postsNum 帖子数最多倒序  peopleNum 人数最多倒序  否则按贴吧id
     * @param categoryId 查询该分类下的贴吧
     * @return 符合条件的贴吧列表 以及 当前用户加入
     */
    @Override
    public Result getRvcBarList(Integer getRecommendBars, String unameIndex, String searchWd, Integer searchType, String sortType, Integer categoryId) {

        List<PostBar> set_recommend = query().eq("SET_RECOMMEND", getRecommendBars).list();
        set_recommend.stream().forEach((PostBar postBar) ->{
            int barId = postBar.getId();
            postBar.setPeopleNum(userBarService.getCount(barId));
            postBar.setPostNum(postFeign.getPostNumByBarId(barId));
        });
        return Result.ok(set_recommend);
    }

    @Override
    public Result getDetailedBar(String uname, int barId) {
        //查询barid对应贴吧所有信息
        PostBar postBar = getById(barId);
        int count = userBarService.getCount(barId);
        postBar.setPeopleNum(count);
        Category category = categoryFeign.getById(barId);
        postBar.setCategory(category.getName());
        Integer num = postFeign.getPostNumByBarId(barId);//
        postBar.setPostNum(num);
        if (uname==null){
            return Result.ok(postBar);
        }
        boolean relevancy = userBarService.getUserBarRelevancy(uname, barId);//查询当前登录用户是否关注了该贴吧

        return Result.ok(postBar,relevancy);
    }

    @Override
    public Result joinBar(int barId, String uname) {

        return Result.ok(userBarService.joinBar(barId,uname));
    }

    @Override
    public Result exitBar(int barId, String uname) {
        return Result.ok(userBarService.exitBar(barId,uname));
    }
}
